package com.sjft.cloud.commons.security.provider;

import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.SpringSecurityCoreVersion;

import java.util.Collection;

/**
 * ConnectAuthToken 主要用于第三方账号关联
 *
 * @author Jin
 */
public class ConnectAuthToken extends AbstractAuthenticationToken {

    private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID;
    private final Object principal;
    private boolean loginFailCreate = false;
    private Integer userType = null;

    public ConnectAuthToken(String principal) {
        super(null);
        this.principal = principal;
        setAuthenticated(false);
    }

    public ConnectAuthToken(String principal, boolean loginFailCreate, int userType) {
        super(null);
        this.principal = principal;
        this.loginFailCreate = loginFailCreate;
        this.userType = userType;
        setAuthenticated(false);
    }

    public ConnectAuthToken(Collection<? extends GrantedAuthority> authorities, Object principal, boolean loginFailCreate) {
        super(authorities);
        this.principal = principal;
        this.loginFailCreate = loginFailCreate;
        super.setAuthenticated(true);
    }

    public ConnectAuthToken(Object principal,
                            Collection<? extends GrantedAuthority> authorities) {
        super(authorities);
        this.principal = principal;
        super.setAuthenticated(true);
    }

    @Override
    public Object getCredentials() {
        return null;
    }

    @Override
    public Object getPrincipal() {
        return this.principal;
    }

    public boolean isLoginFailCreate() {
        return loginFailCreate;
    }

    @Override
    public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException {
        if (isAuthenticated) {
            throw new IllegalArgumentException(
                    "Cannot set this token to trusted - use constructor which takes a GrantedAuthority list instead");
        }
        super.setAuthenticated(false);
    }

    @Override
    public void eraseCredentials() {
        super.eraseCredentials();
    }
}
